package bTree.LeetCode;

public class 岛屿数量dfs {
    int res = 0;
    int[][] dir = {{1, 0}, {0, 1},{0,-1},{-1,0}};

    public int numIslands(char[][] grid) {
        int row = grid.length;
        int line = grid[0].length;
        boolean[][] visited = new boolean[row][line];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < line; j++) {
                char c = grid[i][j];
                if (c == '1' && !visited[i][j]) {
                    res++;
                    dfs(grid, i, j, visited);
                }
            }
        }
        return res;
    }

    private void dfs(char[][] grid, int i, int j, boolean[][] visited) {
        visited[i][j] = true;
        for (int i1 = 0; i1 < 4; i1++) {
            int newX = i + dir[i1][0];
            int newY = j + dir[i1][1];
            if (newX >= grid.length ||newX<0||newY<0|| newY >= grid[0].length || grid[newX][newY] != '1'||visited[newX][newY]) {
                continue;
            }
            dfs(grid, newX, newY, visited);
        }
    }
}
